﻿using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Simple.Common;

namespace Simple.CMS.Web.Authorization
{
    /// <summary>
    /// 授权Session
    /// </summary>
    public class AuthorizeSession
    {
        private const string SessionKey = "SignInData";

        /// <summary>
        /// 设置登录信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="data"></param>
        public static void SignIn(HttpContext httpContext, object data)
        {
            if (httpContext.Session != null)
            {
                httpContext.Session.SetString(SessionKey, data.ToJson());
            }
        }

        public static AuthorizeData GetAuthorizeData(HttpContext httpContext)
        {
            if (httpContext.Session != null)
                return httpContext.Session.GetString(SessionKey).Deserialize<AuthorizeData>();
            return null;
        }

        public static ClaimsPrincipal GetPrincipal(HttpContext httpContext)
        {
            if (httpContext.Session != null)
            {
                var data = httpContext.Session.GetString(SessionKey);
                if (!data.IsNullOrEmpty())
                {
                    var d = data.Deserialize<AuthorizeData>();
                    if (d != null)
                    {
                        var identity = new AdminIdentity { Name = d.LoginName, UserId = d.UserId };
                        identity.Roles.Add(d.Role.ToString());
                        return new ClaimsPrincipal(identity);
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="httpContext"></param>
        public static void SignOut(HttpContext httpContext)
        {
            httpContext.Session.Remove(SessionKey);
        }
    }
}
